package io.renren.common.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

/**
 * MultipartFile
 */
public class HttpIOUtil {
    private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");// 边界标识
    private final static String PREFIX = "--";// 必须存在
    private final static String LINE_END = "\r\n";

    /**
     * POST Multipart Request
     *
     * @param requestUrl  请求url
     * @param requestText 请求参数
     * @param requestFile 请求上传的文件
     * @return
     * @throws Exception
     * @Description:
     */
    public static String sendRequest(String requestUrl,
                                     Map<String, String> requestText, MultipartFile requestFile) throws Exception {
        HttpURLConnection conn = null;
        InputStream input = null;
        OutputStream os = null;
        BufferedReader br = null;
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 10);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.connect();

            // 往服务器端写内容 也就是发起http请求需要带的参数
            os = new DataOutputStream(conn.getOutputStream());
            // 请求参数部分
            writeParams(requestText, os);
            // 请求上传文件部分
            writeFile(requestFile, os);
            // 请求结束标志
            String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
            os.write(endTarget.getBytes());
            os.flush();

            if (conn.getResponseCode() == 200) {
                input = conn.getInputStream();
            } else {
                input = conn.getErrorStream();
            }

            br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            //......
            System.out.println("返回报文:" + buffer.toString());

        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }

                if (os != null) {
                    os.close();
                    os = null;
                }

                if (br != null) {
                    br.close();
                    br = null;
                }
            } catch (IOException ex) {
                throw new Exception(ex);
            }
        }
        return buffer.toString();
    }


    /**
     * 对post参数进行编码处理并写入数据流中
     *
     * @throws Exception
     * @throws IOException
     */
    private static void writeParams(Map<String, String> requestText,
                                    OutputStream os) throws Exception {
        try {

            if (requestText != null && !requestText.isEmpty()) {
                StringBuilder requestParams = new StringBuilder();
                Set<Entry<String, String>> set = requestText.entrySet();
                Iterator<Entry<String, String>> it = set.iterator();
                while (it.hasNext()) {
                    Entry<String, String> entry = it.next();
                    requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);
                    requestParams.append("Content-Type: text/plain; charset=utf-8").append(LINE_END);
                    requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
                    requestParams.append(LINE_END);// 参数头设置完以后需要两个换行，然后才是参数内容
                    requestParams.append(entry.getValue());
                    requestParams.append(LINE_END);
                }
                os.write(requestParams.toString().getBytes());
                os.flush();
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 对post上传的文件进行编码处理并写入数据流中
     *
     * @throws IOException
     */
    private static void writeFile(MultipartFile file,
                                  OutputStream os) throws Exception {
        InputStream is = null;

        try {

            StringBuilder requestParams = new StringBuilder();

            requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
            requestParams.append("Content-Disposition: form-data; name=\"").append("billfile").append("\"; filename=\"").append(file.getOriginalFilename()).append("\"").append(LINE_END);
            requestParams.append("Content-Type:").append(file.getContentType()).append(LINE_END);
            requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
            requestParams.append(LINE_END);// 参数头设置完以后需要两个换行，然后才是参数内容

            os.write(requestParams.toString().getBytes());
            os.write(file.getBytes());
            os.write(LINE_END.getBytes());
            os.flush();

        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                throw new Exception(e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
//		String requestURL = "http://127.0.0.1:9002/ivpay/upLoadBillFile";
        String requestURL = "http://128.1.108.56:8088/immovablespay/ivpay/upLoadBillFile";
        HttpIOUtil httpReuqest = new HttpIOUtil();

        Map<String, String> requestText = new HashMap<String, String>();
        requestText.put("sig", "File_123456");
        Map<String, MultipartFile> requestFile = new HashMap<String, MultipartFile>();

        String picPath = "D:\\CCB_EBSClient_B2C4FileCert_V5.9.3_Build20190827\\download\\SHOP20191113.txt";
        File file = new File(picPath);

        MultipartFile multipartFile = null;

        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("billfile", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());

        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        multipartFile = new CommonsMultipartFile(fileItem);

        String ret = httpReuqest.sendRequest(requestURL, requestText, multipartFile);
    }


}